# -*- coding: UTF-8 -*-
import commands
import json
import logging
import socket

import conf
import power_helper
from utils import ip_utils

logger = logging.getLogger('report')


def send_request_info():
    device_id = ip_utils.get_device_info()
    local_ip = ip_utils.get_local_ip(conf.ifname)
    param = {
        "cmd_type": "InitInfo_report",
        "model_id": device_id,
        "model_type": 2,
        "params": {
            "wcdmaip": local_ip,
            "wcdmaport": conf.web_port
        }
    }
    post(json.dumps(param), port=10010)


def get_device_status():
    return commands.getoutput(
        """sh /root/ucn_app/ucn_status.sh |wc -l |awk '{if($0==5){print "active"}else{print "inactive"}}'""")


def get_device_power_status():
    status = power_helper.get_power_status()
    if status == '-1':
        return 'timeout'
    if status == '00':
        return 'active'
    else:
        return 'alarm'


def send_mormal_heart():
    try:
        local_ip = ip_utils.get_local_ip(conf.ifname)
        device_id = ip_utils.get_device_info()
        # send_request_info()
        power_status = get_device_power_status()
        status = get_device_status()
        heart_params = {
            "cmd_type": "DeviceHeart_report",
            "model_id": device_id,
            "params": {
                "ip": local_ip,
                "port": conf.web_port,
                "status": status,
                "power_status": power_status
            }
        }
        logger.info('normal report param :' + json.dumps(heart_params, ensure_ascii=True))
        post(json.dumps(heart_params), port=conf.udp_port)
        return True
    except Exception as e:
        logger.error('send_mormal_heart error' + str(e))
        # conf.udp_port = 10010
        # send_request_info()
    return False


def post(data, port=conf.udp_port):
    logger.info(str(port) + '--' + data)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(20)
    s.sendto(data, (conf.udp_server, port))
    s.close()
